import {
	doLogin
} from "@/api/user.js"
import store from '@/store/index.js'

const getCode = () => {
	return new Promise((rel, rej) => {
		uni.login({
			provider: 'univerify',
			success(e) {
				rel(e.code)
			}
		})
	})
}

const autoLogin = async (token = '') => {
	if (token) {
		return store.dispatch('app/setToken', token)
		return
	}
	const codes = await getCode()
	const {
		code,
		data,
		msg
	} = await doLogin({
		code: codes
	})
	if (code !== 200) {
		// store.dispatch('app/overFirst')
		return
	}
	if (data.is_register) {
		return store.dispatch('app/setToken', data.token)
	} else {
		store.dispatch('app/setOpenId', data)
		return new Promise((rel) => {
			rel(false)
		})
	}
}

export default {
	autoLogin
}